package team.yidong.fenda.serviceImpl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.entity.Hospital;
import team.yidong.fenda.entity.Master;
import team.yidong.fenda.entity.MasterScore;
import team.yidong.fenda.repository.HospitalRepository;
import team.yidong.fenda.repository.MasterRepository;
import team.yidong.fenda.repository.MasterScoreRepository;
import team.yidong.fenda.service.MasterScoreService;
import team.yidong.fenda.utils.MasterScoreTiXian;

import javax.persistence.criteria.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by xuanlong on 2017/10/29.
 */
@Service
public class MasterScoreServiceImpl implements MasterScoreService {
    @Autowired
    MasterScoreRepository masterScoreRepository;
    @Autowired
    HospitalRepository hospitalRepository;
    @Autowired
    MasterRepository masterRepository;
    @Autowired
    MasterScoreTiXian masterScoreTiXian;

    @Override
    public JSONObject findMasterScore(Integer hospitalId, Integer offset, Integer limit, String hospitalName, String masterName, String startDate, String endDate, String status, String tixianDate, String tixianDate1) {
        Page<MasterScore> masterScorePage;
        Pageable pageable = new PageRequest(offset, limit, Sort.Direction.ASC, "creatDate");
        masterScorePage = masterScoreRepository.findAll(new Specification<MasterScore>() {
            List<Predicate> predicateList = new ArrayList<>();

            @Override
            public Predicate toPredicate(Root<MasterScore> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                if (hospitalId != 1) {
                    Predicate p = criteriaBuilder.equal(root.get("masterScoreAnswer").get("master").get("hospital").get("id"), hospitalId);
                    predicateList.add(p);
                }
                if (hospitalName != null && !hospitalName.equals("")) {
                    Predicate p = criteriaBuilder.equal(root.get("masterScoreAnswer").get("master").get("hospital").get("name"), hospitalName);
                    predicateList.add(p);
                }
                if (masterName != null && !masterName.equals("")) {

                    Predicate p = criteriaBuilder.like(root.get("masterScoreAnswer").get("master").get("name"), "%" + masterName + "%");
                    predicateList.add(p);
                }
                if (startDate != null && !startDate.equals("")) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date start = formatter.parse(startDate);
                        Predicate p = criteriaBuilder.greaterThanOrEqualTo(root.get("creatDate").as(Date.class), start);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (endDate != null && !startDate.equals("")) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date end = formatter.parse(endDate);
                        Predicate p = criteriaBuilder.lessThanOrEqualTo(root.get("creatDate").as(Date.class), end);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (tixianDate != null && !tixianDate.equals("")) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date tixian = formatter.parse(tixianDate);
                        Predicate p = criteriaBuilder.greaterThanOrEqualTo(root.get("scoreBecomeMoneyTime").as(Date.class), tixian);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (tixianDate1 != null && !tixianDate1.equals("")) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date tixian1 = formatter.parse(tixianDate1);
                        Predicate p = criteriaBuilder.lessThanOrEqualTo(root.get("scoreBecomeMoneyTime").as(Date.class), tixian1);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (status != null && !status.equals("")) {
                    if ("yes".equals(status)) {
                        Predicate predicate = criteriaBuilder.equal(root.get("status"), "已提现");
                        predicateList.add(predicate);
                    } else if ("no".equals(status)) {
                        Predicate predicate = criteriaBuilder.equal(root.get("status"), "未提现");
                        predicateList.add(predicate);
                    } else if ("wu".equals(status)) {
                        Predicate predicate = criteriaBuilder.equal(root.get("status"), "免费问题无积分");
                        predicateList.add(predicate);
                    } else if ("chu".equals(status)) {
                        Predicate predicate = criteriaBuilder.equal(root.get("status"), "初始积分");
                        predicateList.add(predicate);
                    }

                }
                Predicate predicate = criteriaBuilder.notEqual(root.get("masterScoreAnswer").get("isBlack"), "是");
                predicateList.add(predicate);
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        }, pageable);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"hospitalPermissionSet", " masterScoreSet", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", "masterScore", "masterAnswerList", "praiseUserSet", "questionURLSet", "answerList", "orderQuestion"});
        JSONObject jsonObject = JSONObject.fromObject(masterScorePage, jsonConfig);
        String temp = "{\"total\":" + jsonObject.getString("totalElements") + ",\"rows\":" + jsonObject.getString("content") + "}";
        JSONObject j = JSONObject.fromObject(temp);


        //计算总积分
        List<MasterScore> masterScoreList = masterScoreRepository.findAll(new Specification<MasterScore>() {
            List<Predicate> predicateList = new ArrayList<>();

            @Override
            public Predicate toPredicate(Root<MasterScore> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                if (hospitalId != 1) {
                    Predicate p = criteriaBuilder.equal(root.get("masterScoreAnswer").get("master").get("hospital").get("id"), hospitalId);
                    predicateList.add(p);
                }
                if (hospitalName != null && !hospitalName.equals("")) {
                    Predicate p = criteriaBuilder.equal(root.get("masterScoreAnswer").get("master").get("hospital").get("name"), hospitalName);
                    predicateList.add(p);
                }
                if (masterName != null && !masterName.equals("")) {

                    Predicate p = criteriaBuilder.like(root.get("masterScoreAnswer").get("master").get("name"), "%" + masterName + "%");
                    predicateList.add(p);
                }
                if (startDate != null && !startDate.equals("")) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date start = formatter.parse(startDate);
                        Predicate p = criteriaBuilder.greaterThanOrEqualTo(root.get("creatDate").as(Date.class), start);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (endDate != null && !startDate.equals("")) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date end = formatter.parse(endDate);
                        Predicate p = criteriaBuilder.lessThanOrEqualTo(root.get("creatDate").as(Date.class), end);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (tixianDate != null && !tixianDate.equals("")) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date tixian = formatter.parse(tixianDate);
                        Predicate p = criteriaBuilder.greaterThanOrEqualTo(root.get("scoreBecomeMoneyTime").as(Date.class), tixian);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (tixianDate1 != null && !tixianDate1.equals("")) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date tixian1 = formatter.parse(tixianDate1);
                        Predicate p = criteriaBuilder.lessThanOrEqualTo(root.get("scoreBecomeMoneyTime").as(Date.class), tixian1);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (status != null && !status.equals("")) {
                    if ("yes".equals(status)) {
                        Predicate predicate = criteriaBuilder.equal(root.get("status"), "已提现");
                        predicateList.add(predicate);
                    } else if ("no".equals(status)) {
                        Predicate predicate = criteriaBuilder.equal(root.get("status"), "未提现");
                        predicateList.add(predicate);
                    }

                }
                Predicate predicate = criteriaBuilder.notEqual(root.get("masterScoreAnswer").get("isBlack"), "是");
                predicateList.add(predicate);
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        });
        Double sum = new Double(0);

        for (MasterScore masterScore : masterScoreList) {
            sum += Double.parseDouble(masterScore.getNum().toString());
        }
        j.put("sum", new java.text.DecimalFormat("#.00").format(sum));
        return j;

    }


    @Transactional
    @Override
    public void deleteMasterScore(Iterable<MasterScore> masterScoreIterable) {
        masterScoreRepository.delete(masterScoreIterable);
    }

    @Transactional
    @Override
    public void updateMasterScore(MasterScore masterScore) {
        masterScoreRepository.save(masterScore);
    }

    @Transactional
    @Override
    public void masterScoreToMoney(Integer tixianTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Hospital hospital = hospitalRepository.findByTixianTime(tixianTime);
        List<Master> masterList = hospital.getMasterList();
        for (Master master : masterList) {
            Double sum = 0.0;
            List<MasterScore> masterScoreList = masterScoreRepository.findByStatusAndMaster(master.getId(), "未提现");
            for (MasterScore masterScore : masterScoreList) {
                sum += masterScore.getNum();
            }
            masterScoreTiXian.tixian(sum, master.getOpenId());
            for (MasterScore masterScore : masterScoreList) {
                masterScore.setStatus("已提现");
                masterScore.setScoreBecomeMoneyTime(formatter.format(new Date()));
                masterScoreRepository.save(masterScore);
            }

        }
    }
}
